<template>
  <ul class="switch_bar">
    <li
      class="switch_bar-li"
      v-for="item in list"
      :key="item.code"
      :style="`margin-left: ${liMarginLeft}px`"
      :class="{active: activeCode === item.code}"
      @click="toggleSwitch(item.code)">{{item.name}}</li>
      <!-- 滑块 -->
    <li class="switch_bar-move" :style="switchBarStyle"></li>
  </ul>
</template>

<script>
export default {
  props: ['list', 'value'],
  data () {
    return {
      // li标签margin-left值
      liMarginLeft: 6
    }
  },
  computed: {
    // 当前激活的index
    activeCode: {
      get () {
        return this.value
      },
      set (value) {
        this.$emit('input', value)
      }
    },
    // 滑块的动态属性
    switchBarStyle () {
      const index = this.list.findIndex(x => x.code === this.activeCode) || 0
      // left 值，绝对定位
      let left = 0
      left += index * 100 / this.list.length
      return { width: `${100 / this.list.length}%`, left: `${left}%` }
    }
    // isLoading: () => store.isLoading
  },
  methods: {
    // 切换
    toggleSwitch (code) {
      if (this.isLoading) return false
      this.activeCode = code
      this.$emit('change', code)
    }
  },
  mounted () {
    // 动态获取元素列表的宽度
    // const elWidthList = document.getElementsByClassName('switch_bar-li')
    // for (let i = 0; i < elWidthList.length; i++) {
    //   let el = elWidthList[i]
    //   this.elWidthList.push(el.clientWidth)
    // }
  }
}
</script>

<style lang="less" scoped>
  /** 主题切换相关 */
    @switch-bk: #1F2745;
    @switch-text: #D2D7ED;
    @switch-text-acitve: #547AFF;
    @switch-item-bk-acitve: #13192F;
    // 调用css函数
    .init-theme();

  .init-theme () {
    .switch_bar {
      margin-top: 1.5625rem /* 25/16 */;
      margin-bottom: 1.875rem /* 30/16 */;
      padding: 2px;
      display: flex;
      align-items: center;
      border-radius: .25rem /* 4/16 */;
      background-color: @switch-bk;
      position: relative;
      .switch_bar-li {
        flex: 1;
        padding: 0 1rem /* 16/16 */;
        height: 2rem /* 32/16 */;
        cursor: pointer;
        line-height: 2rem /* 32/16 */;
        text-align: center;
        color: @switch-text;
        font-size: .875rem /* 14/16 */;
        transition: all 0.28s;
        z-index: 1;
        &:first-child {
          margin-left: 0 !important;
        }
        &.active {
          color: @switch-text-acitve;
          font-weight: bold;
        }
      }
      .switch_bar-move {
        position: absolute;
        left: -3.75rem /* 60/16 */;
        top: .125rem /* 2/16 */;
        height: 2rem /* 32/16 */;
        width: 3.75rem /* 60/16 */;
        background-color: @switch-item-bk-acitve;
        z-index: 0;
        transition: all .28s cubic-bezier(.4,-.3,.57,1.38);
      }
    }
  }
</style>
